package com.cloudcc.mobile.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Environment;
/**
 *多图片一起上传
 * @author Administrator
 *
 */
public class UploadClient {
	@SuppressLint("SimpleDateFormat")
	public static String sendMany(String[] uploadFiles, String actionUrl){
		try {
			for (int i = 0; i < uploadFiles.length; i++) {
				File file = new File(uploadFiles[i]);
				if (!file.exists() || !file.isFile()) {
					return null;
				}
			}
			/**			 * 第一部分			 */
			URL urlObj = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

			/**			 * 设置关键值			 */
			con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			con.setConnectTimeout(30000);//超时时间
			con.setReadTimeout(30000);
			
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");

			// 设置边界
			String BOUNDARY = "----------" + System.currentTimeMillis();

			con.setRequestProperty("Content-Type", "multipart/mixed; boundary="
					+ BOUNDARY);

			// con.setRequestProperty("content-type",
			// "multipart/form-data; boundary=" + BOUNDARY);
			// con.setRequestProperty("content-type", "text/html");
			// 请求正文信息

			OutputStream out = new DataOutputStream(con.getOutputStream());
			for (int i = 0; i < uploadFiles.length; i++) {
				String filePath=uploadFiles[i];
				Bitmap bitmap=ImageUtils.getImg(filePath,480f,800f);
				byte[] imagebyte=ImageUtils.compressBitmap(bitmap,100f);
				SimpleDateFormat formatter=new SimpleDateFormat ("yyyyMMddHHmmss");     
				Date curDate= new Date(System.currentTimeMillis());//获取当前时间     
				String time=formatter.format(curDate);

				String picPath=ImageUtils.SaveImage(time+".jpg", imagebyte);
				File file = new File(picPath);
				if (!file.exists() || !file.isFile()) {
					return null;
				}
				StringBuilder sb = new StringBuilder();
				sb.append("--"); // ////////必须多两道线
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data;name=\"file" + i + 1
						+ "\";filename=\"" + file.getName() + "\"\r\n");
				sb.append("Content-Type:application/octet-stream\r\n\r\n");
				byte[] head = sb.toString().getBytes("utf-8");
				// 获得输出流

				out.write(head);
				//OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");

				// 文件正文部分
				DataInputStream in = new DataInputStream(new FileInputStream(file));
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				out.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个
				in.close();
				//删除这个文件
				String imagepath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/CloudCC/Download/"+time+".jpg";
				FileUtil.deleteFile(imagepath);
			}

			// 第一部分：
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
			/**
			 * 读取服务器响应，必须读取,否则提交不成功
			 */
			// return con.getResponseCode();
			int res= con.getResponseCode();
			if(res!=200){
				return null;
			}
			/**
			 * 下面的方式读取也是可以的
			 */
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			StringBuilder sbString = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sbString.append(line + "\n");  
			}
			reader.close(); 
			con.disconnect();  
			return sbString.toString();
		} catch (Exception e) {
			Tools.i("outtime", "ConnectTimeoutException");
			Tools.handle(e);
			return "null";
		}
	}
//-----------------------------------------------------------------------------------------------------------------
	/**
	 * @param url 请求地址 
	 * @param filePath 文件在服务器保存路径（这里是为了自己测试方便而写，可以将该参数去掉）
	 * @return 
	 * @throws IOException    
	 */
	public int send(String url, String filePath) throws IOException {

		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			return -1;
		}
		/**
		 * 第一部分
		 */
		URL urlObj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		/**
		 * 设置关键值
		 */
		con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用缓存
		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();

		con.setRequestProperty("Content-Type", "multipart/mixed; boundary="
				+ BOUNDARY);

		// con.setRequestProperty("content-type",
		// "multipart/form-data; boundary=" + BOUNDARY);
		// con.setRequestProperty("content-type", "text/html");
		// 请求正文信息

		// 第一部分：
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // ////////必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
				+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		byte[] head = sb.toString().getBytes("utf-8");
		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		out.write(head);
		OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");

		// 文件正文部分
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();
		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
		out.write(foot);
		out.flush();
		out.close();
		/**
		 * 读取服务器响应，必须读取,否则提交不成功
		 */
		// return con.getResponseCode();
		con.getResponseCode();

		/**
		 * 下面的方式读取也是可以的
		 */

		try {

			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		return 1;

	}

	public void upload() {
		List<String> list = new ArrayList<String>(); //要上传的文件名,如：d:\haha.doc.你要实现自己的业务。我这里就是一个空list.
		list.add("c:\\22.jpg");
		list.add("c:\\11.jpg");
		try {
			String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
			URL url = new URL(
					"http://test.cloudcc.cn/distributor.action?serviceName=uploadImg&binding=C5EB824FEB3D7AB43CCF5296453AA8BA&data={\"imgName\":\"imgName\",\"imgType\":\"png\",\"imgWidth\":null,\"imgHeight\":null,\"imgId\":\"\"}");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Charsert", "UTF-8");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
			int leng = list.size();
			for (int i = 0; i < leng; i++) {
				String fname = list.get(i);
				File file = new File(fname);
				StringBuilder sb = new StringBuilder();
				sb.append("--");
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data;name=\"file" + i
						+ "\";filename=\"" + file.getName() + "\"\r\n");
				sb.append("Content-Type:application/octet-stream\r\n\r\n");

				byte[] data = sb.toString().getBytes();
				out.write(data);
				DataInputStream in = new DataInputStream(new FileInputStream(
						file));
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				out.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个
				in.close();
			}
			out.write(end_data);
			out.flush();
			out.close();

			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}

		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
	}

	//	// http://test.cloudcc.cn/querysome.action?m=viewImg&fileid=1405483290798nmNIxQrx!4fc6067f917f39da72e9b156063b4d6e
	//	public static void main(String[] args) throws Exception {
	//		try{
	//			String url_str = "http://test.cloudcc.cn/distributor.action";
	//			String data_login = "serviceName=clogin&userName=admin@cctest.com&password=111111";	
	//			String login_str = HTTPServiceOperate.operate(url_str, data_login);
	//			JSONObject login = new JSONObject(login_str);
	//			String binding = login.getString("binding");
	//			System.out.println("binding:"+binding);
	//			
	//			UploadClient up = new UploadClient();
	//			// System.out.println(up.send("http://localhost:8080/uploadTest/filterfileupload",
	//			// "c:\\Ascent.jpg"));
	//	
	//			// System.out.println(up.send("http://localhost:8080/uploadTest/upload/uploadFile.do?a=cc",
	//			// "c:\\Ascent.jpg"));
	//	
	//			//  System.out.println(up.send("http://test.cloudcc.cn/distributor.action?serviceName=uploadImg&binding=C5EB824FEB3D7AB43CCF5296453AA8BA&data={\"imgName\":\"imgName\",\"imgType\":\"png\",\"imgWidth\":null,\"imgHeight\":null,\"imgId\":\"\"}","c:\\11.jpg"));
	//	
	//			//        System.out.println(up.send("http://test.cloudcc.cn/distributor.action?serviceName=uploadFile&binding=838384CBB0665ECF8FF295DEBE671369"
	//			//                                                        + "&relatedId=b07201300001483589Nn",
	//			//                                                        "c:\\11.jpg"));
	//			
	//			//上传多张图片
	//			String actionUrl = "http://test.cloudcc.cn/distributor.action?serviceName=uploadImgMany&binding="+binding+"&" +
	//					"data=[{\"imgName\":\"imgName\",\"imgType\":\"png\",\"imgWidth\":null,\"imgHeight\":null,\"imgId\":\"\"},{\"imgName\":\"imgName1\",\"imgType\":\"png\",\"imgWidth\":null,\"imgHeight\":null,\"imgId\":\"\"}]";
	//			String[] filePaths = new String[2];
	//			filePaths[0] = "c:\\22.jpg";
	//			filePaths[1] = "c:\\11.jpg";
	//			up.sendMany(filePaths, actionUrl);
	//		}catch(Exception e){e.printStackTrace();}
	//
	//		//  up.upload();
	//
	//	}

}
